<template>
    <div class="elderly-profile-management">
        <!-- 搜索筛选区域 -->
        <div class="query-section">
            <el-card shadow="never" class="query-card">
                <el-form :model="queryParams" ref="queryFormRef" class="query-form" label-width="80px">
                    <el-row :gutter="20">
                        <!-- 姓名 -->
                        <el-col :xs="24" :sm="12" :md="8" :lg="6">
                            <el-form-item label="姓名:" prop="fullName">
                                <el-input
                                v-model.trim="queryParams.fullName"
                                placeholder="请输入姓名"
                                clearable
                                @keyup.enter="handleQuery"
                                />
                            </el-form-item>
                        </el-col>

                        <!-- 身份证号 -->
                        <el-col :xs="24" :sm="12" :md="8" :lg="6">
                            <el-form-item label="身份证号:" prop="idCardNumber">
                                <el-input
                                v-model.trim="queryParams.idCardNumber"
                                placeholder="请输入身份证号"
                                clearable
                                @keyup.enter="handleQuery"
                                />
                            </el-form-item>
                        </el-col>

                        <!-- 性别 -->
                        <el-col :xs="24" :sm="12" :md="8" :lg="6">
                            <el-form-item label="性别:" prop="gender">
                                <el-select
                                v-model="queryParams.gender"
                                placeholder="请选择性别"
                                clearable
                                style="width: 100%"
                                @change="handleQuery"
                                >
                                <el-option label="全部" value="" />
                                <el-option label="男" value="男" />
                                <el-option label="女" value="女" />
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <!-- 操作按钮 -->
                        <el-col :xs="24" :sm="12" :md="8" :lg="6">
                            <el-form-item label-width="0" class="action-buttons-wrapper">
                                <el-button type="primary" @click="handleQuery" :loading="loading" icon="Search">
                                查询
                                </el-button>
                                <el-button @click="resetQuery" icon="Refresh">重置</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-card>
        </div>

        <!-- 固定的操作栏 -->
        <div class="action-section">
            <el-card shadow="never" class="action-card">
                <div class="action-bar">
                    <div class="action-left">
                        <!-- 刷新按钮 -->
                        <el-button type="info" icon="Refresh" @click="handleRefresh" :loading="loading">
                            <i class="el-icon-refresh"></i> 刷新
                        </el-button>

                        <!-- 新增档案按钮 -->
                        <el-button type="success" icon="Plus" @click="openAddProfileDialog">
                            <i class="el-icon-plus"></i> 新增档案
                        </el-button>

                        <!-- 批量删除按钮 -->
                        <el-button type="danger" icon="Delete" @click="handleBatchDelete" :disabled="!selectedProfiles.length">
                            <i class="el-icon-delete"></i> 批量删除
                        </el-button>
                    </div>
                    <!-- 条目信息 -->
                    <div class="total-info">
                        共 <strong class="total-count">{{ totalItems }}</strong> 条记录
                    </div>
                </div>
            </el-card>
        </div>

        <!-- 3. 可滚动的内容区域 -->
        <div class="content-section" ref="contentSectionRef">
            <el-card shadow="never" class="content-card">
                <!-- 桌面端表格 -->
                <div v-if="isDesktop" class="desktop-table">
                    <el-table
                    :data="elderlyProfiles"
                    border
                    stripe
                    v-loading="loading"
                    element-loading-text="加载中..."
                    style="width: 100%; max-width: 1280px;"
                    v-model:selection="selectedProfiles"
                    @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="55"></el-table-column>
                        <el-table-column label="姓名" prop="fullName" align="center" />
                        <el-table-column label="身份证号" prop="idCardNumber" align="center" />
                        <el-table-column label="性别" prop="gender" align="center" />
                        <el-table-column label="出生日期" prop="dateOfBirth" align="center" />
                        <el-table-column label="健康状况" prop="healthStatus" align="center" />
                        <el-table-column label="住址" prop="address" align="center" />
                        <el-table-column label="紧急联系人" prop="emergencyContactName" align="center" />
                        <el-table-column label="紧急联系电话" prop="emergencyContactPhone" align="center" />
                        <el-table-column label="在住状态" prop="checkInStatus" align="center">
                            <template #default="{ row }">
                                <el-tag :type="getCheckInStatusTagType(row.checkInStatus)" effect="light">
                                    {{ row.checkInStatus }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="床位号" prop="bedId" align="center" />
                        <el-table-column label="操作" align="center" width="180">
                            <template #default="{ row }">
                                <div class="table-actions">
                                    <el-button text type="primary" size="small" icon="View" @click="viewProfile(row.id)">
                                        查看
                                    </el-button>
                                    <el-button text type="danger" size="small" icon="Delete" @click="deleteProfile(row.id)">
                                        删除
                                    </el-button>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>

                <!-- 移动端卡片列表 -->
                <div v-else class="mobile-list" :style="{ height: mobileListHeight }">
                    <el-empty v-if="!elderlyProfiles.length && !loading" description="未查询到相关档案" />
                    <div v-for="item in elderlyProfiles" :key="item.id" class="mobile-card">
                        <!-- 选择框 -->
                        <el-checkbox v-model="selectedProfiles" class="mobile-checkbox"></el-checkbox> 

                        <!-- 各用户卡片 -->
                        <div class="card-header">
                            <div class="header-left">
                                <span class="elderly-name">{{ item.fullName }}</span>
                                <span class="id-card">{{ item.idCardNumber }}</span>
                            </div>
                            <el-tag :type="getCheckInStatusTagType(item.checkInStatus)" size="small" effect="light">
                                {{ item.checkInStatus }}
                            </el-tag>
                        </div>
                        <div class="card-body">
                            <div class="info-row">
                                <span class="info-label">性别</span>
                                <span class="info-value">{{ item.gender }}</span>
                            </div>
                            <div class="info-row">
                                <span class="info-label">出生日期</span>
                                <span class="info-value">{{ item.dateOfBirth }}</span>
                            </div>
                            <div class="info-row">
                                <span class="info-label">健康状况</span>
                                <span class="info-value">{{ item.healthStatus }}</span>
                            </div>
                            <div class="info-row">
                                <span class="info-label">住址</span>
                                <span class="info-value">{{ item.address }}</span>
                            </div>
                            <div class="info-row">
                                <span class="info-label">紧急联系人</span>
                                <span class="info-value">{{ item.emergencyContactName }} ({{ item.emergencyContactPhone }})</span>
                            </div>
                            <div class="info-row">
                                <span class="info-label">床位号</span>
                                <span class="info-value">{{ item.bedId }}</span>
                            </div>
                        </div>
                        <div class="card-actions">
                            <el-button text type="primary" size="small" icon="View" @click="viewProfile(item.id)">
                                查看
                            </el-button>
                            <el-button text type="danger" size="small" icon="Delete" @click="deleteProfile(item.id)">
                                删除
                            </el-button>
                        </div>
                    </div>
                </div>
            </el-card>
        </div>

        <!-- 4. 固定的分页栏 -->
        <div class="pagination-section">
            <el-pagination
                @current-change="handlePageChange"
                :page-size="pageSize"
                :current-page="currentPage"
                :total="totalItems"
                layout="total, prev, pager, next, jumper"
                class="pagination-container"
                background
            ></el-pagination>
        </div>

        <!-- 添加档案弹框 -->
        <el-dialog title="添加老人档案" v-model="addProfileDialogVisible" width="50%">
            <el-form :model="newProfile" ref="profileForm" label-width="110px">

                <!-- ！！通过用户名搜索来添加档案 -->
                <!-- <el-form-item label="选择用户" :rules="[{ required: true, message: '请选择用户', trigger: 'change' }]">
                <el-autocomplete
                    v-model="searchQuery"
                    :fetch-suggestions="searchUsers"
                    placeholder="请输入用户名搜索"
                    @select="handleUserSelect"
                    :loading="loading">
                    <template #suffix>
                    <i class="el-icon-search"></i>
                    </template>
                </el-autocomplete>
                </el-form-item> -->

                <el-form-item label="姓名" :rules="[{ required: true, message: '请输入姓名', trigger: 'blur' }]">
                    <el-input v-model="newProfile.fullName" placeholder="请输入姓名"></el-input>
                </el-form-item>

                <el-form-item label="身份证号" :rules="[{ required: true, message: '请输入身份证号', trigger: 'blur' }]">
                    <el-input v-model="newProfile.idCardNumber" placeholder="请输入身份证号"></el-input>
                </el-form-item>

                <el-form-item label="性别" :rules="[{ required: true, message: '请选择性别', trigger: 'change' }]">
                    <el-select v-model="newProfile.gender" placeholder="请选择性别">
                        <el-option label="男" value="男"></el-option>
                        <el-option label="女" value="女"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="出生日期">
                    <el-date-picker v-model="newProfile.dateOfBirth" type="date" placeholder="请选择出生日期"></el-date-picker>
                </el-form-item>

                <el-form-item label="健康状况">
                    <el-input v-model="newProfile.healthStatus" placeholder="请输入健康状况"></el-input>
                </el-form-item>

                <el-form-item label="住址">
                    <el-input v-model="newProfile.address" placeholder="请输入住址"></el-input>
                </el-form-item>

                <el-form-item label="紧急联系人" :rules="[{ required: true, message: '请输入紧急联系人姓名', trigger: 'blur' }]">
                    <el-input v-model="newProfile.emergencyContactName" placeholder="请输入紧急联系人姓名"></el-input>
                </el-form-item>

                <el-form-item label="紧急联系电话" :rules="[{ required: true, message: '请输入紧急联系电话', trigger: 'blur' }]">
                    <el-input v-model="newProfile.emergencyContactPhone" placeholder="请输入紧急联系电话"></el-input>
                </el-form-item>

                <el-form-item label="在住状态" :rules="[{ required: true, message: '请选择在住状态', trigger: 'change' }]">
                    <el-select v-model="newProfile.checkInStatus" placeholder="请选择在住状态">
                        <el-option label="在住" value="在住"></el-option>
                        <el-option label="临时外出" value="临时外出"></el-option>
                        <el-option label="退住" value="退住"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="床位">
                    <el-input v-model="newProfile.bedId" placeholder="请输入床位号"></el-input>
                </el-form-item>
            </el-form>

            <template v-slot:footer>
                <el-button @click="addProfileDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitProfile">确 定</el-button>
            </template>
        </el-dialog>

    </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, computed, nextTick } from 'vue';
import axios from 'axios';
import { ElMessage, ElNotification, ElMessageBox } from 'element-plus';
import { Search, Refresh, Plus, Delete, View } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import request from '@/utils/request';

const router = useRouter();

// 处理电脑端与手机端之间的转换
const screenWidth = ref(window.innerWidth);
const screenHeight = ref(window.innerHeight);
const isDesktop = computed(() => screenWidth.value >= 768);
const containerWidth = ref(0);
const contentSectionRef = ref(null);

const mobileListHeight = computed(() => {
  const topOffset = 290;
  const calculatedHeight = screenHeight.value - topOffset;
  return `${calculatedHeight > 200 ? calculatedHeight : 200}px`;
});

let resizeObserver = null;

onMounted(() => {
  window.addEventListener('resize', handleResize);
  fetchData();

  nextTick(() => {
    if (contentSectionRef.value && window.ResizeObserver) {
      resizeObserver = new ResizeObserver(entries => {
        if (entries[0]) {
          containerWidth.value = entries[0].contentRect.width;
        }
      });
      resizeObserver.observe(contentSectionRef.value);
    } else {
      handleResize();
    }
  });
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  if (resizeObserver) {
    resizeObserver.disconnect();
  }
});

const handleResize = () => {
  screenWidth.value = window.innerWidth;
  screenHeight.value = window.innerHeight;
  if (contentSectionRef.value) {
    containerWidth.value = contentSectionRef.value.offsetWidth;
  }
};

// 存储数据
const elderlyProfiles = ref([]);  // 存储老人档案列表
const pageSize = ref(10)  // 每页展示的条数
const currentPage = ref(1)  // 当前页
const totalItems = ref(50)  // 总条数
const loading = ref(false);       // 加载状态
const selectedProfiles = ref([]); // 存储批量删除时选中的档案
const profileForm = ref(null); // 使用 ref 存储 el-form 实例

// 存储查询条件
const queryParams = ref({
  fullName: '',         // 姓名
  idCardNumber: '',     // 身份证号
  gender: '',           // 性别
  page: 1,              // 当前页码
  size: 10,             // 每页显示的记录数
});

// 查询函数 - 用于模糊查询
const handleQuery = async () => {
  // console.log('触发查询');
  queryParams.value.page = 1;  // 每次查询时，重置为第一页
  await nextTick(() => {
    fetchData();  // 调用 fetchData 方法发起查询请求
  });
};

// 获取老人档案数据
const fetchData = async () => {
  loading.value = true;
  try {
    const response = await request.get('/elderly/search', {
      params: {
        fullName: queryParams.value.fullName,
        idCardNumber: queryParams.value.idCardNumber,
        gender: queryParams.value.gender,
        page: queryParams.value.page,    // 当前页码
        size: queryParams.value.size,    // 每页记录数
      }
    });


    elderlyProfiles.value = response.records;
    totalItems.value = response.total; // 更新总记录数，用于分页组件

  } catch (error) {
    console.error('获取数据失败:', error);
  } finally {
    loading.value = false;
  }
};

// 重置查询条件
const resetQuery = () => {
  queryParams.value.fullName = '';
  queryParams.value.idCardNumber = '';
  queryParams.value.gender = '';
  queryParams.value.page = 1;   // 重置为第一页
  refreshTable();  // 重置后重新获取数据
};

// 处理分页页码变化
const handlePageChange = (page) => {
  currentPage.value = page
  refreshTable();
}

// 刷新老人档案列表
const refreshTable = async () => {
  try {
    const response = await request.get(`/elderly/list?page=${currentPage.value}&size=${pageSize.value}`)
    elderlyProfiles.value = response.records
    totalItems.value = response.total
  } catch (error) {
    console.error('获取老人档案列表失败:', error)
  }
}

// 刷新功能
const handleRefresh = () => {
  refreshTable();  // 刷新按钮的功能，重新获取数据
};

// 弹框控制
const addProfileDialogVisible = ref(false)
const newProfile = ref({
  userId: '888',  // 设置一个默认的 userId 作为占位符
  fullName: '',
  idCardNumber: '',
  gender: '',
  dateOfBirth: '',
  healthStatus: '',
  address: '',
  emergencyContactName: '',
  emergencyContactPhone: '',
  checkInStatus: '在住',  // 默认在住状态
  bedId: ''
})

const selectedProfile = ref({})  // 编辑用的已选档案

// 打开添加档案弹框
const openAddProfileDialog = () => {
  addProfileDialogVisible.value = true;
};

// 提交新增档案数据
const submitProfile = async () => {
  // 表单验证
  try {
    // 如果表单没有通过验证，直接返回
    const isValid = await validateForm();
    if (!isValid) {
      console.log('表单验证未通过');
      return;
    }

    // 防止重复提交
    addProfileDialogVisible.value = false;

    // 发送新增档案请求
    const response = await request.post('/elderly', newProfile.value);

    // 成功后刷新表格并关闭弹框
    refreshTable();
    // 弹出成功提示
    ElMessage.success('老人档案添加成功！');
  } catch (error) {
    // 捕获并处理错误
    console.error('新增老人档案失败:', error);
    ElMessage.error('提交失败，请稍后重试');
  } finally {

  }
};

// 表单验证方法
const validateForm = () => {
  return new Promise((resolve, reject) => {
    // 调用 el-form 的验证方法
    const form = profileForm.value;
    form.validate((valid) => {
      if (valid) {
        resolve(true);
      } else {
        resolve(false);
      }
    });
  });
};

// 选择框
const handleSelectionChange = (val) => {
  selectedProfiles.value = val;
  console.log('选择变化:', val);  // 查看选择变化时的数据
};

// 批量删除操作
const handleBatchDelete = async () => {
  // 在删除前打印选中的记录
  // console.log("选中的记录:", selectedProfiles.value);

  if (selectedProfiles.value.length === 0) {
    ElMessage.warning('请先选择要删除的档案');
    return;
  }

  // 弹出确认删除的弹框
  ElMessageBox.confirm(
    '您确定要删除选中的档案吗？', // 提示文本
    '警告', // 标题
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      // 用户点击确认时，执行批量删除操作
      try {
        const ids = selectedProfiles.value.map(profile => profile.id);  // 提取选中的档案ID
        const response = await response.delete('/elderly/batch', { data: ids });  // 批量删除请求
        if (response.status === 200) {
          ElMessage.success('批量删除成功');
          refreshTable();  // 删除后重新获取数据
        }
      } catch (error) {
        console.error('批量删除失败:', error);
        ElMessage.error('批量删除失败，请稍后重试');
      }
    })
    .catch(() => {
      // 用户点击取消时的操作
      ElMessage.info('删除操作已取消');
    });
};

// 查看档案详情
const viewProfile = (id) => {
  console.log(`查看档案 ID: ${id}`);
  // 跳转到档案详情页面
  router.push({ name: 'ElderlyDetail', params: { id } });
};

// 删除单个档案
const deleteProfile = async (id) => {
  // 弹出确认删除的弹框
  ElMessageBox.confirm(
    '您确定要删除此档案吗？', // 提示文本
    '警告', // 标题
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning', // 设置为警告类型
    }
  )
    .then(async () => {
      // 用户点击确认时，执行删除操作
      try {
        const response = await axios.delete(`/elderly/${id}`);  // 删除请求
        if (response.status === 200) {
          ElMessage.success('删除成功');
          refreshTable();  // 删除后重新获取数据
        }
      } catch (error) {
        console.error('删除失败:', error);
        ElMessage.error('删除失败，请稍后重试');
      }
    })
    .catch(() => {
      // 用户点击取消时的操作
      ElMessage.info('删除操作已取消');
    });
};

// 获取在住状态标签类型
const getCheckInStatusTagType = (status) => {
  switch (status) {
    case '在住':
      return 'success';
    case '临时外出':
      return 'warning';
    case '退住':
      return 'danger';
    default:
      return 'info';
  }
};

refreshTable();  // 初始加载数据
</script>


<style scoped>
.elderly-profile-management {
  width: 99%;
  height: 100vh;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
}

.query-section,
.action-section {
  flex-shrink: 0;
}

.pagination-section {
  flex-shrink: 0;
}

.content-section {
  flex: 1;
  min-height: 0;
  position: relative;
}

.query-card,
.action-card,
.content-card {
  border: none;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
}

.content-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.content-card ::v-deep .el-card__body {
  flex: 1;
  min-height: 0;
  overflow: hidden;
  padding: 10px;
}

.query-form .action-buttons-wrapper ::v-deep .el-form-item__content {
  display: flex;
  gap: 10px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.total-info {
  font-size: 14px;
  color: #606266;
}

.total-info ::v-deep .total-count {
  color: var(--el-color-primary);
  font-size: 16px;
  font-weight: 600;
  margin: 0 4px;
}

.desktop-table,
.mobile-list {
  height: 100%;
  width: 100%;
}

.desktop-table {
  display: flex;
  /* 水平居中 */
  overflow-x: auto;
  /* 启用水平滚动条 */
  overflow-y: auto;
  /* 启用垂直滚动条 */
  max-height: 500px;
  /* 限制表格的最大高度 */
}

.desktop-table ::v-deep .el-table {
  max-width: 1200px;
  /* 设置最大宽度，防止过宽 */
  width: 100%;
  /* 占满可用宽度，但不超过max-width */
}

.mobile-list {
  overflow-y: auto;
}

.amount-text,
.amount-highlight {
  font-weight: 600;
  color: #e65d5d;
}

.amount-highlight {
  font-size: 16px;
}

.text-muted {
  color: #a8abb2;
}

/* 手机端 */
.mobile-list .mobile-card {
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: box-shadow 0.3s ease, transform 0.3s ease;
}

.mobile-list .mobile-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.mobile-list .card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f2f5;
  gap: 8px;
}

.mobile-list .card-header .header-left {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.mobile-list .card-header .elderly-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.mobile-list .card-header .bill-month {
  font-size: 13px;
  color: #909399;
}

.mobile-list .card-body {
  padding: 12px 0;
}

.mobile-list .card-body .info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  font-size: 14px;
}

.mobile-list .card-body .info-row .info-label {
  color: #606266;
}

.mobile-list .card-body .info-row .info-value {
  color: #303133;
  font-weight: 500;
}

.mobile-list .card-body .info-row.amount-row .info-value {
  font-size: 16px;
}

.mobile-list .card-actions {
  padding-top: 12px;
  border-top: 1px solid #f0f2f5;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding-top: 16px;
}
</style>